package com.jar.springbootsecuritydemo.config;


import com.jar.springbootsecuritydemo.pojo.bo.SecurityUser;
import com.jar.springbootsecuritydemo.pojo.entity.SysUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 *
 *SpringSecurity用户工厂类
 */
public final class SecurityUserFactory {

    private SecurityUserFactory() {
    }

    /**
     * 通过管理员Admin，生成一个SpringSecurity用户
     *
     * @param user
     * @return
     */
    public static SecurityUser create(SysUser user) {
        boolean enabled = "1".equals(user.getStatus());
        return new SecurityUser(
                user.getUserId().toString(),
                user.getUserName(),
                user.getPassword(),
                enabled,
                mapToGrantedAuthorities(user.getSysRoles()),
                null
        );
    }
    public static SecurityUser create(SysUser user, Set<String> permission) {
        boolean enabled = "1".equals(user.getStatus());
        return new SecurityUser(
                user.getUserId().toString(),
                user.getUserName(),
                user.getPassword(),
                enabled,
                mapToGrantedAuthorities(user.getSysRoles()),
                permission
        );
    }

    private static List<GrantedAuthority> mapToGrantedAuthorities(List<String> authorities) {
        return authorities.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }

}
